package com.sinosoft.common.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.nutz.lang.Mirror;

/**
 * 对象操作类
 * @author unhappydepig 
 * @mail yqw8912@163.com
 * @time 2015-4-27 下午5:53:53
 */
public class BeanUtil {
	/**
	 * key =className +fieldName
	 */
	private static Map<String,Integer> fieldMap = new HashMap<String,Integer>();
	/**
	 * 根据对象及属性名获取属性值
	 * @param bean
	 * @param property
	 * @return
	 */
	public static Object getProperty(Object obj, String property) {
		Mirror<?> mirror = Mirror.me(obj.getClass());		
		Object v = mirror.getValue(obj, property);
		return v;
	}
	/**
	 *  给对象赋值
	 * @param obj
	 * @param fieldName
	 * @param objValue
	 */
	public static void setValue(Object obj,String fieldName,Object objValue){
		Mirror mirror = Mirror.me(obj.getClass());	
		try {
			Method setter = mirror.getSetter(fieldName, objValue.getClass());
		} catch (NoSuchMethodException e) {
			return;
		}
		mirror.setValue(obj, fieldName, objValue);
	}
	/**
	 *  对象取值
	 * @param obj
	 * @param fieldName
	 * @param objValue
	 */
	public static Object getValue(Object obj,String fieldName){
		Mirror mirror = Mirror.me(obj.getClass());
		return mirror.getValue(obj, fieldName);
	}	
	/**
	 * 获取某个属性是否是数据库属性
	 * @param obj
	 * @param field
	 * @return
	 */
	public static boolean getDbFlag(Object obj,Field field){
		String key = obj.getClass().getName()+"."+field.getName();
		if(fieldMap.containsKey(key)){
			int fieldFlag = fieldMap.get(key);
			if(0==fieldFlag){
				return false;
			}
			return true;
		}
		for(Annotation ation:field.getAnnotations()){
			String annotationName = ation.annotationType().getSimpleName();
			if("Column".equals(annotationName)){
				fieldMap.put(key, 1);
				return true;
			}
		}
		fieldMap.put(key, 0);
		return false;
	}
	
}
